package handler

import (
	"fmt"
	"google.golang.org/protobuf/proto"
	"src/model/ProtoModel"
	"src/service"
	"src/utils"
	"strings"
)

// subscribe 订阅逻辑
type RedisHandler struct {
}

// 用户发起请求触发 ws链接 绑定触发
func (*RedisHandler) RedisHandler(channelName string, msg []byte) error {
	this := RedisHandler{}
	act, dateType, databuf, err := utils.MessageF.UnpackMessage(msg)
	if err != nil {
		fmt.Println(dateType, act, databuf, err)
		return err
	}
	switch dateType {
	case ProtoModel.SendTypeProto_MESSAGE:
		var msgArr = ProtoModel.MessagesPubProto{}
		err = proto.Unmarshal(databuf.Bytes(), &msgArr)
		if err != nil {

			return err
		}
		err := this.onMessage(act, &msgArr)
		if err != nil {
			return err
		}
	case ProtoModel.SendTypeProto_SENT:
	case ProtoModel.SendTypeProto_REPLY:
	}
	return nil
}
func (r *RedisHandler) onMessage(actType ProtoModel.SendActProto, msgArr *ProtoModel.MessagesPubProto) error {

	var err error
	defer func() {
		if err != nil {
			//清除链接状态 以及全局缓存数据
		}
	}()
	switch actType {
	case ProtoModel.SendActProto_SENDALL:
		//给所有人广播
		service.GetMessage().SendMsgArrToAll(msgArr.Msg)
	case ProtoModel.SendActProto_SENDLIST:
		//遍历消息 推送给接收人
		service.GetMessage().SendMsgArrToUserAll(msgArr.Msg)
	case ProtoModel.SendActProto_SENDUIDS:
		//遍历消息 推送给指定用户下的
		//逗号分割多个用户
		var uids = strings.Split(msgArr.Uid, ",")
		service.GetMessage().SendMsgArrToUsers(msgArr.Msg, uids)
	case ProtoModel.SendActProto_SENDDID:
		service.GetMessage().SendMsgArrToFd(msgArr.Msg, msgArr.Did)
	case ProtoModel.SendActProto_SENDUID:
		//msgArr:=msgArr.Msg
		service.GetMessage().SendMsgArrToUser(msgArr.Msg, msgArr.Uid)
	case ProtoModel.SendActProto_SENDUIDDID:
		service.GetMessage().SendMsgArrToUserFd(msgArr.Msg, msgArr.Uid, msgArr.Did)
	case ProtoModel.SendActProto_SENDOTHER:

	case ProtoModel.SendActProto_SENDROOM:

		service.GetMessage().SendMsgListToRoom(msgArr.Msg, msgArr.Uid)
	default:

	}
	if err != nil {
		return err
	}
	return nil
}
